package br.com.negocio;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.dao.DAOFactory;
import br.com.dao.ItemDAO;
import br.com.item.Item;
import br.com.util.HibernateUtil;

public class ItemService {

	public void salvar(Item item){
		
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(item);
		tx.commit();
		session.close();
	}
	
	
	public ArrayList<Item> listarTodos(){
		Session session = HibernateUtil.getSession();
		List list = session.createQuery("from Item").list();
		return (ArrayList<Item>) list;
		
	}
	
	public List<String> pesquisarDescricoes(String descricao) {
		DAOFactory daoFactory = DAOFactory.getDAOFactory();
		ItemDAO itemDAO = daoFactory.getItemDAO();
		List<String> descricoes = itemDAO.pesquisarDescricoes(descricao);
		daoFactory.encerrar();
		return descricoes;
	}
	
	
	public Item pesquisarPorId(int codigo) {
		Session session = HibernateUtil.getSession();
		try {
			return (Item) session.get(Item.class, codigo);
		} finally {
			session.close();
		}
	}
	
	public void excluir(Item item){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.delete(item);
		tx.commit();
		session.close();
	}
	
	public ArrayList<Item> consultaLike(String descricao){
		Session session = HibernateUtil.getSession();
		
		List list = session.createQuery("from Item i WHERE i.descricao like :desc").setParameter("desc", "%" +  descricao + "%").list();	
		return (ArrayList<Item>) list;
		
	}
	
}
